package dai.core.base

import org.lwjgl.opengl.GL11C.*
import org.lwjgl.opengl.GL30C.glGenerateMipmap
import org.lwjgl.stb.STBImage.stbi_image_free
import org.lwjgl.stb.STBImage.stbi_load
import org.lwjgl.system.MemoryStack.stackPush
import java.lang.RuntimeException
import java.nio.ByteBuffer

class Texture(filename:String) {

    companion object{
        fun loadTexture(filename:String):Int{
            val width:Int
            val height:Int
            val buf:ByteBuffer
            stackPush().use {stack->
                val w = stack.mallocInt(1)
                val h = stack.mallocInt(1)
                val channels = stack.mallocInt(1)
                buf = stbi_load(filename,w,h,channels,4) ?: throw RuntimeException("load image file:${filename} error!")
                width = w.get()
                height = h.get()
            }

            val textureId = glGenTextures()
            glBindTexture(GL_TEXTURE_2D,textureId)
            glPixelStorei(GL_UNPACK_ALIGNMENT,1)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
            glTexImage2D(GL_TEXTURE_2D,0, GL_RGBA,width,height,0, GL_RGBA, GL_UNSIGNED_BYTE,buf)

            // 产生 mipmap
            glGenerateMipmap(GL_TEXTURE_2D)
            stbi_image_free(buf)
            return  textureId
        }
    }

    val texId:Int = loadTexture(filename)

    fun bind(){
        glBindTexture(GL_TEXTURE_2D,texId)
    }

    fun cleanup(){
        glDeleteTextures(texId)
    }
}